/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.base.connection.session;

import com.google.common.base.Strings;
import com.je.connector.base.cache.CacheKeys;
import com.je.connector.base.config.InstantConfig;
import com.je.connector.base.connection.SessionContext;
import com.je.connector.base.utils.MD5Utils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 可恢复Session管理器
 *
 * @ProjectName: instant-message
 * @Package: com.connector.base.connection.session
 * @ClassName: ResuableSessionManager
 * @Description: 可恢复Session管理器
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
public class ResuableSessionManager {

    private final int expiredTime = InstantConfig.server.sessionExpiredTime;
    private final ConcurrentMap<String, String> LOCAL_CACHE = new ConcurrentHashMap<>();

    public boolean cacheSession(ResuableSession session) {
        String key = CacheKeys.getSessionKey(session.getSessionId());
        LOCAL_CACHE.putIfAbsent(key, ResuableSession.encode(session.getContext()));
        return true;
    }

    public ResuableSession querySession(String sessionId) {
        String key = CacheKeys.getSessionKey(sessionId);
        String value = LOCAL_CACHE.get(key);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return ResuableSession.decode(value);
    }

    public ResuableSession genSession(SessionContext context) {
        long now = System.currentTimeMillis();
        ResuableSession session = new ResuableSession();
        session.setContext(context);
        session.setSessionId(MD5Utils.encrypt(context.getDeviceId() + now));
        session.setExpireTime(now + expiredTime * 1000);
        return session;
    }
}
